{% extends "base.html" %}

{% block title %}分析报告 - SurveyAnalyzer{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{{ url_for('main.index') }}">
                <i class="fas fa-home me-1"></i>
                首页
            </a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">
            <i class="fas fa-file-alt me-1"></i>
            分析报告
        </li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 报告操作面板 -->
    <div class="col-md-3 mb-4">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-tools me-2"></i>
                    报告操作
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-primary" onclick="generateReport()">
                        <i class="fas fa-plus me-1"></i>
                        生成新报告
                    </button>
                    <button class="btn btn-outline-secondary" onclick="loadTemplate()">
                        <i class="fas fa-file-import me-1"></i>
                        加载模板
                    </button>
                    <button class="btn btn-outline-info" onclick="previewReport()" id="previewBtn" disabled>
                        <i class="fas fa-eye me-1"></i>
                        预览报告
                    </button>
                </div>
                
                <hr>
                
                <div class="mb-3">
                    <label for="reportTitle" class="form-label">报告标题</label>
                    <input type="text" class="form-control" id="reportTitle" value="问卷调查分析报告">
                </div>
                
                <div class="mb-3">
                    <label for="reportAuthor" class="form-label">报告作者</label>
                    <input type="text" class="form-control" id="reportAuthor" value="SurveyAnalyzer">
                </div>
                

                

                
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="useAiInsights" checked>
                    <label class="form-check-label" for="useAiInsights">
                        <i class="fas fa-brain me-1"></i>
                        启用AI智能洞察
                    </label>
                </div>
                

            </div>
        </div>
        

    </div>
    
    <!-- 报告内容 -->
    <div class="col-md-9">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-file-alt me-2"></i>
                    报告内容
                </h5>
                <div>
                    <button class="btn btn-outline-primary btn-sm" onclick="addSection()">
                        <i class="fas fa-plus me-1"></i>
                        添加章节
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" onclick="saveReport()" id="saveBtn" disabled>
                        <i class="fas fa-save me-1"></i>
                        保存报告
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="reportContent" style="min-height: 600px;">
                    <div class="d-flex align-items-center justify-content-center h-100 text-muted">
                        <div class="text-center">
                            <i class="fas fa-file-alt fa-3x mb-3"></i>
                            <p>点击"生成新报告"开始创建分析报告</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 章节编辑模态框 -->
<div class="modal fade" id="sectionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit me-2"></i>
                    编辑章节
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="sectionTitle" class="form-label">章节标题</label>
                    <input type="text" class="form-control" id="sectionTitle">
                </div>
                <div class="mb-3">
                    <label for="sectionType" class="form-label">章节类型</label>
                    <select class="form-select" id="sectionType">
                        <option value="text">文本内容</option>
                        <option value="chart">图表</option>
                        <option value="table">表格</option>
                        <option value="analysis">分析结果</option>
                        <option value="summary">摘要</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="sectionContent" class="form-label">章节内容</label>
                    <textarea class="form-control" id="sectionContent" rows="8"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveSectionEdit()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 报告预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye me-2"></i>
                    报告预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="previewContent">
                    <!-- 预览内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="printReport()">打印</button>
            </div>
        </div>
    </div>
</div>

<style>
.report-section {
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    position: relative;
    transition: all 0.3s ease;
    background: white;
}

.correlation-matrix {
    font-size: 0.85em;
}

.correlation-matrix th,
.correlation-matrix td {
    min-width: 80px;
    text-align: center;
    vertical-align: middle;
}

.correlation-matrix .fw-bold {
    background-color: #f8f9fa;
    text-align: left;
    padding-left: 10px;
}

.table-responsive {
    border-radius: 6px;
    overflow: hidden;
}

.table-striped tbody tr:nth-of-type(odd) {
    background-color: rgba(0,0,0,.02);
}

.table-hover tbody tr:hover {
    background-color: rgba(0,0,0,.05);
}

.report-section[data-section-type="ai_insight"] {
    border-left: 4px solid #007bff;
    background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
}

.report-section:hover {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border-color: #007bff;
}

.section-controls {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.report-section:hover .section-controls {
    opacity: 1;
}

.section-title {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: #495057;
}

.section-title i {
    color: #007bff;
}

.section-content {
    line-height: 1.6;
}

.markdown-content {
    font-size: 1rem;
    line-height: 1.7;
}

.markdown-content p {
    margin-bottom: 1rem;
}

.ai-insight-card {
    background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
    border: 1px solid #bbdefb;
    border-radius: 10px;
    padding: 15px;
    margin: 10px 0;
    position: relative;
    overflow: hidden;
}

.ai-insight-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #2196f3, #9c27b0);
}

.insight-importance-high {
    border-color: #f44336;
}

.insight-importance-high::before {
    background: linear-gradient(to bottom, #f44336, #ff9800);
}

.insight-importance-medium {
    border-color: #ff9800;
}

.insight-importance-medium::before {
    background: linear-gradient(to bottom, #ff9800, #ffc107);
}

.loading-ai {
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: loading 2s infinite;
}

@keyframes loading {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

.insight-category {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: 500;
    margin-right: 8px;
}

.insight-category-correlation {
    background-color: #e3f2fd;
    color: #1976d2;
}

.insight-category-clustering {
    background-color: #f3e5f5;
    color: #7b1fa2;
}

.insight-category-text {
    background-color: #e8f5e8;
    color: #388e3c;
}

.insight-category-business {
    background-color: #fff3e0;
    color: #f57c00;
}

.ai-enhancement-badge {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    padding: 5px 15px;
    border-radius: 20px;
    font-size: 0.9rem;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    margin-top: 10px;
}

.chart-placeholder {
    background: #f8f9fa;
    border: 2px dashed #dee2e6;
    border-radius: 0.375rem;
    padding: 2rem;
    text-align: center;
    color: #6c757d;
}

.report-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 30px;
    border-radius: 10px;
    margin-bottom: 30px;
    text-align: center;
}

.report-title {
    font-size: 2.5rem;
    font-weight: bold;
    margin-bottom: 10px;
    color: white;
}

.report-meta {
    font-size: 1.1rem;
    opacity: 0.9;
    color: white;
}

@media print {
    .section-controls {
        display: none !important;
    }
    
    .report-section {
        break-inside: avoid;
        page-break-inside: avoid;
    }
}
</style>

<script>
let currentReport = null;
let reportSections = [];
let currentEditingSection = null;
const filename = '{{ filename }}';

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否有filename参数
    if (!filename || filename.trim() === '') {
        showNoFileMessage();
        disableReportControls();
    }
    

});



function showNoFileMessage() {
    const contentContainer = document.getElementById('reportContent');
    contentContainer.innerHTML = `
        <div class="d-flex align-items-center justify-content-center h-100">
            <div class="text-center">
                <i class="fas fa-exclamation-triangle fa-3x mb-3 text-warning"></i>
                <h4>需要先上传数据文件</h4>
                <p class="text-muted mb-4">报告功能需要基于已上传的数据文件进行分析</p>
                <div class="d-grid gap-2 d-md-block">
                    <a href="/upload" class="btn btn-primary">
                        <i class="fas fa-upload me-1"></i>
                        上传数据文件
                    </a>
                    <a href="/" class="btn btn-outline-secondary">
                        <i class="fas fa-home me-1"></i>
                        返回首页
                    </a>
                </div>
            </div>
        </div>
    `;
}

function disableReportControls() {
    document.getElementById('previewBtn').disabled = true;
    document.getElementById('exportBtn').disabled = true;
    document.getElementById('saveBtn').disabled = true;
    
    // 禁用生成报告按钮
    const generateBtn = document.querySelector('button[onclick="generateReport()"]');
    if (generateBtn) {
        generateBtn.disabled = true;
        generateBtn.innerHTML = '<i class="fas fa-ban me-1"></i>需要数据文件';
    }
}

function generateReport() {
    // 检查是否有filename
    if (!filename || filename.trim() === '') {
        // 如果没有文件，显示提示信息并重定向到上传页面
        const contentContainer = document.getElementById('reportContent');
        contentContainer.innerHTML = `
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>需要数据文件</strong>
                <p class="mb-2">请先上传数据文件才能生成分析报告。</p>
                <a href="/upload" class="btn btn-primary btn-sm">
                    <i class="fas fa-upload me-1"></i>
                    上传数据文件
                </a>
            </div>
        `;
        return;
    }
    
    const useAiInsights = document.getElementById('useAiInsights').checked;
    
    // 显示加载状态
    const contentContainer = document.getElementById('reportContent');
    const loadingText = useAiInsights ? '正在生成AI智能分析报告...' : '正在生成数据分析报告...';
    contentContainer.innerHTML = `
        <div class="d-flex align-items-center justify-content-center h-100">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">生成中...</span>
                </div>
                <p class="mt-2">${loadingText}</p>
                ${useAiInsights ? '<small class="text-muted">AI正在深度分析数据，请稍候...</small>' : ''}
            </div>
        </div>
    `;
    
    // 调用API生成报告
    const apiEndpoint = `/api/report/${filename}`;
    const requestBody = {
        title: document.getElementById('reportTitle').value,
        author: document.getElementById('reportAuthor').value,
        use_ai_insights: useAiInsights
    };
    
    fetch(apiEndpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            contentContainer.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    生成报告失败：${data.error}
                </div>
            `;
        } else {
            currentReport = data;
            reportSections = data.sections || [];
            displayReport();
            
            enableReportControls();
            
            // 显示AI洞察提示
            if (useAiInsights && data.ai_insights) {
                showAiInsightsNotification(data.ai_insights);
            }
        }
    })
    .catch(error => {
        contentContainer.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                生成报告失败：${error.message}
            </div>
        `;
    });
}



function displayReport(data) {
    if (!data) {
        data = currentReport;
    }
    
    if (!data) {
        return;
    }
    
    currentReport = data;
    
    const container = document.getElementById('reportContent');
    
    // 根据报告类型显示不同内容
    if (data.sections) {
        // 传统章节格式
        reportSections = data.sections;
        let html = `
            <div class="report-header">
                <div class="report-title">${data.title || document.getElementById('reportTitle').value}</div>
                <div class="report-meta">
                    作者：${data.author || document.getElementById('reportAuthor').value} | 
                    生成时间：${new Date(data.generated_at || Date.now()).toLocaleString()}
                    ${data.ai_enhanced ? '<span class="badge bg-primary ms-2"><i class="fas fa-brain me-1"></i>AI增强版</span>' : ''}
                </div>
            </div>
        `;
        
        reportSections.forEach((section, index) => {
            html += `
                <div class="report-section" data-section-index="${index}" data-section-type="${section.type || 'default'}">
                    <div class="section-controls">
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editSection(${index})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger me-1" onclick="deleteSection(${index})">
                            <i class="fas fa-trash"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="moveSection(${index}, 'up')">
                            <i class="fas fa-arrow-up"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="moveSection(${index}, 'down')">
                            <i class="fas fa-arrow-down"></i>
                        </button>
                    </div>
                    <div class="section-title">${section.title}</div>
                    <div class="section-content">
                        ${renderSectionContent(section)}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    } else if (data.report) {
        // 新的智能报告格式
        displayIntelligentReport(data.report);
    } else {
        // 兼容旧格式
        let html = `
            <div class="report-header">
                <div class="report-title">${document.getElementById('reportTitle').value}</div>
                <div class="report-meta">
                    作者：${document.getElementById('reportAuthor').value} | 
                    生成时间：${new Date().toLocaleString()}
                </div>
            </div>
        `;
        
        reportSections.forEach((section, index) => {
            html += `
                <div class="report-section" data-section-index="${index}">
                    <div class="section-controls">
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editSection(${index})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger me-1" onclick="deleteSection(${index})">
                            <i class="fas fa-trash"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="moveSection(${index}, 'up')">
                            <i class="fas fa-arrow-up"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="moveSection(${index}, 'down')">
                            <i class="fas fa-arrow-down"></i>
                        </button>
                    </div>
                    <div class="section-title">${section.title}</div>
                    <div class="section-content">
                        ${renderSectionContent(section)}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    }
}



function displayIntelligentReport(report) {
    const container = document.getElementById('reportContent');
    let html = '';
    
    // 报告头部
    html += `
        <div class="report-header">
            <div class="report-title">智能数据分析报告</div>
            <div class="report-meta">
                生成时间：${new Date(report.generated_at || Date.now()).toLocaleString()}
                ${report.ai_enhanced ? '<span class="badge bg-primary ms-2"><i class="fas fa-brain me-1"></i>AI增强版</span>' : ''}
            </div>
            ${report.data_summary ? `
                <div class="mt-2">
                    <small class="text-muted">
                        数据规模：${report.data_summary.rows || 'N/A'} 行 × ${report.data_summary.columns || 'N/A'} 列
                        ${report.analysis_modules ? ' | 分析模块：' + report.analysis_modules.join(', ') : ''}
                    </small>
                </div>
            ` : ''}
        </div>
    `;
    
    // 执行摘要
    if (report.content && typeof report.content === 'string') {
        html += `
            <div class="report-section">
                <div class="section-title"><i class="fas fa-chart-line me-2"></i>执行摘要</div>
                <div class="section-content">
                    <div class="markdown-content">${formatMarkdownContent(report.content)}</div>
                </div>
            </div>
        `;
    } else if (report.content && typeof report.content === 'object') {
        // 综合报告格式
        if (report.content.executive_summary) {
            html += `
                <div class="report-section">
                    <div class="section-title"><i class="fas fa-chart-line me-2"></i>执行摘要</div>
                    <div class="section-content">
                        <div class="markdown-content">${formatMarkdownContent(report.content.executive_summary)}</div>
                    </div>
                </div>
            `;
        }
        
        // 数据概览
        if (report.content.data_overview) {
            html += `
                <div class="report-section">
                    <div class="section-title"><i class="fas fa-database me-2"></i>数据概览</div>
                    <div class="section-content">
                        ${formatDataOverview(report.content.data_overview)}
                    </div>
                </div>
            `;
        }
        
        // 详细分析
        if (report.content.detailed_analysis) {
            html += `
                <div class="report-section">
                    <div class="section-title"><i class="fas fa-microscope me-2"></i>详细分析</div>
                    <div class="section-content">
                        ${formatDetailedAnalysis(report.content.detailed_analysis)}
                    </div>
                </div>
            `;
        }
        
        // 描述性统计
        if (report.descriptive_statistics) {
            html += `
                <div class="report-section">
                    <div class="section-title"><i class="fas fa-chart-bar me-2"></i>描述性统计</div>
                    <div class="section-content">
                        ${formatStatisticsTable(report.descriptive_statistics)}
                    </div>
                </div>
            `;
        }
        
        // 相关性分析
        if (report.correlation_analysis) {
            html += `
                <div class="report-section">
                    <div class="section-title"><i class="fas fa-project-diagram me-2"></i>相关性分析</div>
                    <div class="section-content">
                        ${formatCorrelationMatrix(report.correlation_analysis)}
                    </div>
                </div>
            `;
        }
    }
    
    // AI洞察
    if (report.insights && report.insights.length > 0) {
        html += `
            <div class="report-section" data-section-type="ai_insight">
                <div class="section-title"><i class="fas fa-brain me-2"></i>智能洞察</div>
                <div class="section-content">
                    ${formatInsights(report.insights)}
                </div>
            </div>
        `;
    }
    
    // 推荐建议
    if (report.content && report.content.recommendations) {
        html += `
            <div class="report-section">
                <div class="section-title"><i class="fas fa-lightbulb me-2"></i>推荐建议</div>
                <div class="section-content">
                    ${formatRecommendations(report.content.recommendations)}
                </div>
            </div>
        `;
    }
    
    container.innerHTML = html;
}

function formatMarkdownContent(content) {
    // 简单的Markdown格式化
    return content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br>')
        .replace(/^(.*)$/, '<p>$1</p>');
}

function formatDataOverview(overview) {
    let html = '<div class="row">';
    
    if (overview.basic_stats) {
        html += `
            <div class="col-md-6">
                <h6>基本统计</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        ${Object.entries(overview.basic_stats).map(([key, value]) => 
                            `<tr><td>${key}</td><td>${value}</td></tr>`
                        ).join('')}
                    </table>
                </div>
            </div>
        `;
    }
    
    if (overview.data_quality) {
        html += `
            <div class="col-md-6">
                <h6>数据质量</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        ${Object.entries(overview.data_quality).map(([key, value]) => 
                            `<tr><td>${key}</td><td>${value}</td></tr>`
                        ).join('')}
                    </table>
                </div>
            </div>
        `;
    }
    
    html += '</div>';
    return html;
}

function formatDetailedAnalysis(analysis) {
    let html = '';
    
    if (typeof analysis === 'string') {
        html = formatMarkdownContent(analysis);
    } else if (typeof analysis === 'object') {
        Object.entries(analysis).forEach(([key, value]) => {
            html += `
                <div class="mb-4">
                    <h6 class="text-primary border-bottom pb-2">${key}</h6>
                    <div>${formatAnalysisValue(key, value)}</div>
                </div>
            `;
        });
    }
    
    return html;
}

function formatAnalysisValue(key, value) {
    // 处理数组类型
    if (Array.isArray(value)) {
        if (value.length === 0) return '<p class="text-muted">无数据</p>';
        return `<ul class="list-unstyled">${value.map(item => `<li class="mb-1">• ${typeof item === 'object' ? formatComplexObject(item) : item}</li>`).join('')}</ul>`;
    }
    
    // 如果是数值型统计数据，格式化为表格
    if (typeof value === 'object' && value !== null) {
        // 检查是否是统计数据格式
        const firstEntry = Object.values(value)[0];
        if (typeof firstEntry === 'object' && firstEntry !== null && 
            ('mean' in firstEntry || 'count' in firstEntry || 'std' in firstEntry)) {
            return formatStatisticsTable(value);
        }
        
        // 检查是否是相关性矩阵
        if (key.toLowerCase().includes('correlation') || key.toLowerCase().includes('相关')) {
            return formatCorrelationMatrix(value);
        }
        
        // 处理复杂嵌套对象
        return formatComplexObject(value);
    }
    
    return typeof value === 'string' ? formatMarkdownContent(value) : String(value);
}

function formatComplexObject(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return String(obj);
    }
    
    // 特殊处理聚类分析结果
    if (obj.cluster_characteristics || obj.centers || obj.feature_names) {
        return formatClusteringResults(obj);
    }
    
    // 特殊处理相关性分析结果
    if (obj.correlation_matrix || obj.significance_matrix || obj.correlation_details) {
        return formatCorrelationResults(obj);
    }
    
    // 特殊处理文本分析结果
    if (obj.keywords || obj.topics || obj.important_keywords || obj.key_topics) {
        return formatTextAnalysisResults(obj);
    }
    
    let html = '<div class="complex-object">';
    
    Object.entries(obj).forEach(([key, value]) => {
        html += `<div class="mb-3">`;
        html += `<h6 class="text-primary border-bottom pb-1">${getDisplayName(key)}</h6>`;
        
        if (typeof value === 'object' && value !== null) {
            if (Array.isArray(value)) {
                if (value.length === 0) {
                    html += '<p class="text-muted ms-2">无数据</p>';
                } else {
                    html += formatArrayValue(key, value);
                }
            } else {
                // 嵌套对象，以卡片形式展示
                 html += '<div class="row ms-1">';
                 Object.entries(value).forEach(([subKey, subValue]) => {
                     html += `
                         <div class="col-md-6 mb-2">
                             <div class="card border-0 bg-light h-100">
                                 <div class="card-body py-2 px-3">
                                     <div class="fw-bold text-secondary small">${getDisplayName(subKey)}</div>
                                     <div class="text-primary">${formatSimpleValue(subValue)}</div>
                                 </div>
                             </div>
                         </div>
                     `;
                 });
                 html += '</div>';
            }
        } else {
            html += `<div class="ms-2">${formatSimpleValue(value)}</div>`;
        }
        
        html += '</div>';
    });
    
    html += '</div>';
    return html;
}

function formatClusteringResults(obj) {
    let html = '<div class="clustering-results">';
    
    // 聚类中心表格
    if (obj.centers && obj.feature_names) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-bullseye me-2"></i>聚类中心特征</h6>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead class="table-dark">
                            <tr>
                                <th>聚类</th>
                                ${obj.feature_names.map(name => `<th>${name}</th>`).join('')}
                            </tr>
                        </thead>
                        <tbody>
                            ${obj.centers.map((center, index) => `
                                <tr>
                                    <td class="fw-bold">群体 ${index + 1}</td>
                                    ${center.map(value => `<td>${Number(value).toFixed(3)}</td>`).join('')}
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    }
    
    // 质量指标
    if (obj.quality_metrics) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-chart-line me-2"></i>聚类质量指标</h6>
                <div class="row">
                    ${Object.entries(obj.quality_metrics).map(([key, value]) => `
                        <div class="col-md-4">
                            <div class="card border-0 bg-light">
                                <div class="card-body text-center py-2">
                                    <div class="fw-bold text-secondary">${getDisplayName(key)}</div>
                                    <div class="h5 mb-0 text-primary">${formatSimpleValue(value)}</div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
    
    // 摘要信息
    if (obj.summary) {
        html += `
            <div class="alert alert-info border-start border-4 border-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>分析摘要：</strong>${obj.summary}
            </div>
        `;
    }
    
    html += '</div>';
    return html;
}

function formatCorrelationResults(obj) {
    let html = '<div class="correlation-results">';
    
    // 相关性矩阵
    if (obj.correlation_matrix) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-table me-2"></i>相关性矩阵</h6>
                ${formatMatrixTable(obj.correlation_matrix, '相关系数')}
            </div>
        `;
    }
    
    // 显著性矩阵
    if (obj.significance_matrix) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-chart-bar me-2"></i>显著性矩阵</h6>
                ${formatMatrixTable(obj.significance_matrix, '显著性水平')}
            </div>
        `;
    }
    
    // 强相关性
    if (obj.strong_correlations && Array.isArray(obj.strong_correlations)) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-link me-2"></i>强相关性</h6>
                <div class="row">
                    ${obj.strong_correlations.map((corr, index) => `
                        <div class="col-md-6 mb-2">
                            <div class="card border-0 bg-light">
                                <div class="card-body py-2">
                                    <div class="fw-bold text-secondary">相关对 ${index + 1}</div>
                                    <div class="text-primary">${formatObjectAsText(corr)}</div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
    
    // 其他属性
    Object.entries(obj).forEach(([key, value]) => {
        if (!['correlation_matrix', 'significance_matrix', 'strong_correlations'].includes(key)) {
            html += `
                <div class="mb-3">
                    <h6 class="text-primary border-bottom pb-1">${getDisplayName(key)}</h6>
                    <div class="ms-2">${formatSimpleValue(value)}</div>
                </div>
            `;
        }
    });
    
    html += '</div>';
    return html;
}

function formatTextAnalysisResults(obj) {
    let html = '<div class="text-analysis-results">';
    
    // 关键词展示
    if (obj.keywords && Array.isArray(obj.keywords)) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-key me-2"></i>重要关键词</h6>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead class="table-dark">
                            <tr>
                                <th>关键词</th>
                                <th>权重</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${obj.keywords.map((keyword, index) => {
                                if (typeof keyword === 'object' && keyword.word) {
                                    return `
                                        <tr>
                                            <td class="fw-bold">${keyword.word}</td>
                                            <td><span class="badge bg-primary">${Number(keyword.score || keyword.weight || 0).toFixed(3)}</span></td>
                                        </tr>
                                    `;
                                } else if (Array.isArray(keyword) && keyword.length >= 2) {
                                    return `
                                        <tr>
                                            <td class="fw-bold">${keyword[0]}</td>
                                            <td><span class="badge bg-primary">${Number(keyword[1]).toFixed(3)}</span></td>
                                        </tr>
                                    `;
                                }
                                return `
                                    <tr>
                                        <td class="fw-bold">关键词 ${index + 1}</td>
                                        <td><span class="badge bg-secondary">未知格式</span></td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    }
    
    // 主题建模展示
    if (obj.topics && Array.isArray(obj.topics)) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-lightbulb me-2"></i>主题分析</h6>
                <div class="row">
                    ${obj.topics.map((topic, index) => {
                        if (typeof topic === 'object' && topic.words && Array.isArray(topic.words)) {
                            return `
                                <div class="col-md-6 mb-3">
                                    <div class="card border-0 bg-light h-100">
                                        <div class="card-body">
                                            <h6 class="card-title text-primary">主题 ${index + 1}</h6>
                                            <div class="mb-2">
                                                ${topic.words.slice(0, 5).map((word, wordIndex) => {
                                                    const weight = topic.weights && topic.weights[wordIndex] ? Number(topic.weights[wordIndex]).toFixed(3) : '';
                                                    return `<span class="badge bg-secondary me-1 mb-1">${word}${weight ? ' (' + weight + ')' : ''}</span>`;
                                                }).join('')}
                                            </div>
                                            ${topic.words.length > 5 ? `<small class="text-muted">还有 ${topic.words.length - 5} 个相关词汇...</small>` : ''}
                                        </div>
                                    </div>
                                </div>
                            `;
                        }
                        return `
                            <div class="col-md-6 mb-3">
                                <div class="card border-0 bg-light h-100">
                                    <div class="card-body">
                                        <h6 class="card-title text-primary">主题 ${index + 1}</h6>
                                        <p class="text-muted">数据格式异常</p>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>
        `;
    }
    
    // 主题建模统计信息
    if (obj.n_topics || obj.perplexity || obj.log_likelihood) {
        html += `
            <div class="mb-4">
                <h6 class="text-primary"><i class="fas fa-chart-line me-2"></i>主题建模统计</h6>
                <div class="row">
                    ${obj.n_topics ? `
                        <div class="col-md-4">
                            <div class="card border-0 bg-light">
                                <div class="card-body text-center py-2">
                                    <div class="fw-bold text-secondary">主题数量</div>
                                    <div class="h5 mb-0 text-primary">${obj.n_topics}</div>
                                </div>
                            </div>
                        </div>
                    ` : ''}
                    ${obj.perplexity ? `
                        <div class="col-md-4">
                            <div class="card border-0 bg-light">
                                <div class="card-body text-center py-2">
                                    <div class="fw-bold text-secondary">困惑度</div>
                                    <div class="h5 mb-0 text-primary">${Number(obj.perplexity).toFixed(3)}</div>
                                </div>
                            </div>
                        </div>
                    ` : ''}
                    ${obj.log_likelihood ? `
                        <div class="col-md-4">
                            <div class="card border-0 bg-light">
                                <div class="card-body text-center py-2">
                                    <div class="fw-bold text-secondary">对数似然</div>
                                    <div class="h5 mb-0 text-primary">${Number(obj.log_likelihood).toFixed(3)}</div>
                                </div>
                            </div>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }
    
    // 其他文本分析属性
    Object.entries(obj).forEach(([key, value]) => {
        if (!['keywords', 'topics', 'n_topics', 'perplexity', 'log_likelihood', 'doc_topic_distribution'].includes(key)) {
            html += `
                <div class="mb-3">
                    <h6 class="text-primary border-bottom pb-1">${getDisplayName(key)}</h6>
                    <div class="ms-2">${formatSimpleValue(value)}</div>
                </div>
            `;
        }
    });
    
    html += '</div>';
    return html;
}

function formatMatrixTable(matrix, title) {
    if (!matrix || typeof matrix !== 'object') {
        return '<p class="text-muted">无矩阵数据</p>';
    }
    
    const variables = Object.keys(matrix);
    if (variables.length === 0) {
        return '<p class="text-muted">无矩阵数据</p>';
    }
    
    let html = `
        <div class="table-responsive">
            <table class="table table-sm table-bordered">
                <thead class="table-dark">
                    <tr>
                        <th>${title}</th>
                        ${variables.map(variable => `<th class="text-center">${variable}</th>`).join('')}
                    </tr>
                </thead>
                <tbody>
    `;
    
    variables.forEach(rowVar => {
        html += `<tr><td class="fw-bold">${rowVar}</td>`;
        variables.forEach(colVar => {
            const value = matrix[rowVar] && matrix[rowVar][colVar];
            const displayValue = typeof value === 'number' ? Number(value).toFixed(3) : (value || '-');
            const cellClass = typeof value === 'number' && Math.abs(value) > 0.7 ? 'bg-warning' : '';
            html += `<td class="text-center ${cellClass}">${displayValue}</td>`;
        });
        html += '</tr>';
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    return html;
}

function formatArrayValue(key, array) {
    // 如果是数值数组且长度适中，显示为表格
    if (array.length <= 20 && array.every(item => typeof item === 'number')) {
        return `
            <div class="table-responsive">
                <table class="table table-sm">
                    <tbody>
                        <tr>
                            ${array.map((item, index) => `<td class="text-center">${Number(item).toFixed(3)}</td>`).join('')}
                        </tr>
                    </tbody>
                </table>
            </div>
        `;
    }
    
    // 其他情况显示为列表
    return `<ul class="list-unstyled ms-2">${array.map(item => `<li class="mb-1">• ${formatSimpleValue(item)}</li>`).join('')}</ul>`;
}

function formatSimpleValue(value) {
    if (value === null || value === undefined) return '<span class="text-muted">-</span>';
    if (typeof value === 'number') {
        return Number.isInteger(value) ? value.toLocaleString() : Number(value).toFixed(3);
    }
    if (typeof value === 'object') {
        if (Array.isArray(value)) {
            return formatArrayAsText(value);
        } else {
            return formatObjectAsText(value);
        }
    }
    return String(value);
}

function formatArrayAsText(array) {
    if (array.length === 0) return '<span class="text-muted">无数据</span>';
    if (array.length <= 5) {
        return array.map(item => typeof item === 'number' ? Number(item).toFixed(3) : String(item)).join(', ');
    }
    return `${array.length} 个项目 (${array.slice(0, 3).map(item => typeof item === 'number' ? Number(item).toFixed(3) : String(item)).join(', ')}...)`;
}

function formatObjectAsText(obj) {
    const entries = Object.entries(obj);
    if (entries.length === 0) return '<span class="text-muted">无数据</span>';
    
    return entries.map(([key, value]) => {
        const displayKey = getDisplayName(key);
        let displayValue;
        
        if (typeof value === 'number') {
            displayValue = Number.isInteger(value) ? value.toLocaleString() : Number(value).toFixed(3);
        } else if (Array.isArray(value)) {
            if (value.length === 0) {
                displayValue = '无数据';
            } else if (key === 'topics') {
                // 特殊处理主题建模结果
                displayValue = formatTopicsArray(value);
            } else if (value.length <= 3) {
                displayValue = value.map(item => typeof item === 'object' ? '复杂对象' : String(item)).join(', ');
            } else {
                displayValue = `${value.length} 个项目`;
            }
        } else if (typeof value === 'object' && value !== null) {
            // 递归处理嵌套对象，但简化显示
            const subEntries = Object.entries(value);
            if (subEntries.length <= 2) {
                displayValue = subEntries.map(([subKey, subValue]) => {
                    const subDisplayValue = typeof subValue === 'number' ? 
                        (Number.isInteger(subValue) ? subValue.toLocaleString() : Number(subValue).toFixed(3)) : 
                        String(subValue);
                    return `${getDisplayName(subKey)}: ${subDisplayValue}`;
                }).join(', ');
            } else {
                displayValue = `包含 ${subEntries.length} 个属性`;
            }
        } else {
            displayValue = String(value);
        }
        
        return `${displayKey}: ${displayValue}`;
    }).join('; ');
}

function formatTopicsArray(topics) {
    if (!Array.isArray(topics) || topics.length === 0) {
        return '无主题数据';
    }
    
    return topics.map((topic, index) => {
        if (typeof topic === 'object' && topic.words && Array.isArray(topic.words)) {
            const topWords = topic.words.slice(0, 3).join(', ');
            return `主题${index + 1}: ${topWords}`;
        }
        return `主题${index + 1}: 复杂对象`;
    }).join('; ');
}

function getDisplayName(key) {
    const displayNames = {
        // 聚类分析
        'cluster_characteristics': '聚类特征',
        'centers': '聚类中心',
        'feature_names': '特征名称',
        'quality_metrics': '质量指标',
        'inertia': '惯性',
        'silhouette_score': '轮廓系数',
        'clustering': '聚类分析',
        
        // 统计分析
        'statistical_analysis': '统计分析',
        'correlation_details': '相关性详情',
        'correlation_matrix': '相关性矩阵',
        'significance_matrix': '显著性矩阵',
        'strong_correlations': '强相关性',
        'method': '方法',
        'pearson': '皮尔逊相关',
        'features_analyzed': '分析特征数',
        'max_correlation': '最大相关性',
        'mean_correlation': '平均相关性',
        'total_pairs': '相关对数',
        'key_findings': '关键发现',
        'normality_tests': '正态性检验',
        'confidence_level': '置信水平',
        'results': '结果',
        'features_tested': '检验特征数',
        'non_normal_features': '非正态特征数',
        'normal_features': '正态特征数',
        'significance_tests': '显著性检验',
        'success': '成功',
        
        // 文本分析
        'text_analysis': '文本分析',
        'important_keywords': '重要关键词',
        'key_topics': '关键主题',
        'keywords': '关键词',
        'topics': '主题',
        'n_topics': '主题数量',
        'perplexity': '困惑度',
        'log_likelihood': '对数似然',
        'doc_topic_distribution': '文档主题分布',
        'total_responses': '总回复数',
        'valid_responses': '有效回复数',
        'total_words': '总词数',
        'unique_words': '唯一词数',
        'top_words': '高频词汇',
        'avg_text_length': '平均文本长度',
        'text_length_stats': '文本长度统计',
        'sentiment_distribution': '情感分布',
        'avg_polarity': '平均极性',
        'avg_subjectivity': '平均主观性',
        'polarity_stats': '极性统计',
        'sentiment_percentages': '情感百分比',
        'subjectivity_stats': '主观性统计',
        'total_analyzed': '分析总数',
        'neutral': '中性',
        'positive': '积极',
        'negative': '消极',
        'error': '错误',
        
        // 通用
        'summary': '摘要',
        'text': '文本',
        'max': '最大值',
        'min': '最小值',
        'std': '标准差',
        'mean': '均值'
    };
    return displayNames[key] || key;
}

function formatStatisticsTable(stats) {
    const variables = Object.keys(stats);
    if (variables.length === 0) return '<p class="text-muted">无统计数据</p>';
    
    // 获取所有可能的统计指标
    const allMetrics = new Set();
    variables.forEach(variable => {
        Object.keys(stats[variable]).forEach(metric => allMetrics.add(metric));
    });
    
    const metrics = Array.from(allMetrics);
    
    let html = `
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>变量</th>
                        ${metrics.map(metric => `<th>${getMetricDisplayName(metric)}</th>`).join('')}
                    </tr>
                </thead>
                <tbody>
    `;
    
    variables.forEach(variable => {
        html += `<tr><td class="fw-bold">${variable}</td>`;
        metrics.forEach(metric => {
            const value = stats[variable][metric];
            html += `<td>${formatStatValue(value)}</td>`;
        });
        html += '</tr>';
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    return html;
}

function formatCorrelationMatrix(matrix) {
    const variables = Object.keys(matrix);
    if (variables.length === 0) return '<p class="text-muted">无相关性数据</p>';
    
    let html = `
        <div class="table-responsive">
            <table class="table table-sm correlation-matrix">
                <thead>
                    <tr>
                        <th></th>
                        ${variables.map(variable => `<th class="text-center">${variable}</th>`).join('')}
                    </tr>
                </thead>
                <tbody>
    `;
    
    variables.forEach(rowVar => {
        html += `<tr><td class="fw-bold">${rowVar}</td>`;
        variables.forEach(colVar => {
            const value = matrix[rowVar] && matrix[rowVar][colVar] !== undefined ? matrix[rowVar][colVar] : 0;
            const cellClass = getCorrelationCellClass(value);
            html += `<td class="text-center ${cellClass}">${formatCorrelationValue(value)}</td>`;
        });
        html += '</tr>';
    });
    
    html += `
                </tbody>
            </table>
        </div>
        <div class="mt-2">
            <small class="text-muted">
                <span class="badge bg-danger me-1">强负相关</span>
                <span class="badge bg-warning me-1">弱相关</span>
                <span class="badge bg-success">强正相关</span>
            </small>
        </div>
    `;
    
    return html;
}

function formatObjectAsTable(obj) {
    let html = `
        <div class="table-responsive">
            <table class="table table-sm">
                <tbody>
    `;
    
    Object.entries(obj).forEach(([key, value]) => {
        html += `<tr><td class="fw-bold">${key}</td><td>${formatStatValue(value)}</td></tr>`;
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    return html;
}

function getMetricDisplayName(metric) {
    const displayNames = {
        'count': '计数',
        'mean': '均值',
        'median': '中位数',
        'std': '标准差',
        'min': '最小值',
        'max': '最大值',
        'q25': '25%分位数',
        'q75': '75%分位数',
        'unique_values': '唯一值数',
        'most_frequent': '最频繁值',
        'most_frequent_count': '最频繁值计数'
    };
    return displayNames[metric] || metric;
}

function formatStatValue(value) {
    if (value === null || value === undefined) return '-';
    if (typeof value === 'number') {
        return Number.isInteger(value) ? value.toLocaleString() : value.toFixed(3);
    }
    return String(value);
}

function formatCorrelationValue(value) {
    if (value === null || value === undefined || isNaN(value)) return '-';
    return Number(value).toFixed(3);
}

function getCorrelationCellClass(value) {
    if (value === null || value === undefined || isNaN(value)) return '';
    const absValue = Math.abs(value);
    if (absValue >= 0.7) {
        return value > 0 ? 'bg-success bg-opacity-25' : 'bg-danger bg-opacity-25';
    } else if (absValue >= 0.3) {
        return 'bg-warning bg-opacity-25';
    }
    return '';
}

function formatInsights(insights) {
    return insights.map(insight => `
        <div class="alert alert-primary border-start border-4 border-primary mb-3">
            <div class="d-flex align-items-start">
                <i class="fas fa-brain me-2 mt-1 text-primary"></i>
                <div>
                    <strong class="text-primary">${insight.title || 'AI洞察'}：</strong>
                    <div class="mt-2">${formatMarkdownContent(insight.content || insight.description || insight)}</div>
                    ${insight.confidence ? `<small class="text-muted mt-2 d-block">置信度: ${Math.round(insight.confidence * 100)}%</small>` : ''}
                </div>
            </div>
        </div>
    `).join('');
}

function formatRecommendations(recommendations) {
    if (typeof recommendations === 'string') {
        return formatMarkdownContent(recommendations);
    } else if (Array.isArray(recommendations)) {
        return recommendations.map(rec => `
            <div class="alert alert-success mb-2">
                <i class="fas fa-lightbulb me-2"></i>
                ${typeof rec === 'string' ? rec : rec.content || rec.description}
            </div>
        `).join('');
    }
    return '';
}

function renderSectionContent(section) {
    switch(section.type) {
        case 'text':
            return `<p>${section.content}</p>`;
            
        case 'chart':
            return `
                <div class="chart-placeholder">
                    <i class="fas fa-chart-bar fa-2x mb-2"></i>
                    <p>${section.content}</p>
                    <small class="text-muted">图表将在导出时生成</small>
                </div>
            `;
            
        case 'table':
            return `
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr><th colspan="100%">${section.content}</th></tr>
                        </thead>
                        <tbody>
                            <tr><td colspan="100%" class="text-muted">表格数据将在导出时生成</td></tr>
                        </tbody>
                    </table>
                </div>
            `;
            
        case 'analysis':
            return `
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    ${section.content}
                </div>
            `;
            
        case 'summary':
            return `
                <div class="alert alert-success">
                    <i class="fas fa-lightbulb me-2"></i>
                    <strong>摘要：</strong>${section.content}
                </div>
            `;
            
        case 'ai_insight':
            return `
                <div class="alert alert-primary border-start border-4 border-primary">
                    <div class="d-flex align-items-start">
                        <i class="fas fa-brain me-2 mt-1 text-primary"></i>
                        <div>
                            <strong class="text-primary">AI智能洞察：</strong>
                            <div class="mt-2">${section.content}</div>
                            ${section.confidence ? `<small class="text-muted mt-2 d-block">置信度: ${Math.round(section.confidence * 100)}%</small>` : ''}
                        </div>
                    </div>
                </div>
            `;
            
        default:
            return `<p>${section.content}</p>`;
    }
}

function addSection() {
    const modal = new bootstrap.Modal(document.getElementById('sectionModal'));
    
    // 清空表单
    document.getElementById('sectionTitle').value = '';
    document.getElementById('sectionType').value = 'text';
    document.getElementById('sectionContent').value = '';
    
    currentEditingSection = null;
    modal.show();
}

function editSection(index) {
    const section = reportSections[index];
    const modal = new bootstrap.Modal(document.getElementById('sectionModal'));
    
    // 填充表单
    document.getElementById('sectionTitle').value = section.title;
    document.getElementById('sectionType').value = section.type;
    document.getElementById('sectionContent').value = section.content;
    
    currentEditingSection = index;
    modal.show();
}

function saveSectionEdit() {
    const title = document.getElementById('sectionTitle').value;
    const type = document.getElementById('sectionType').value;
    const content = document.getElementById('sectionContent').value;
    
    if (!title.trim()) {
        alert('请输入章节标题');
        return;
    }
    
    const section = { title, type, content };
    
    if (currentEditingSection !== null) {
        // 编辑现有章节
        reportSections[currentEditingSection] = section;
    } else {
        // 添加新章节
        reportSections.push(section);
    }
    
    displayReport();
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('sectionModal'));
    modal.hide();
}

function deleteSection(index) {
    if (confirm('确定要删除这个章节吗？')) {
        reportSections.splice(index, 1);
        displayReport();
    }
}

function moveSection(index, direction) {
    if (direction === 'up' && index > 0) {
        [reportSections[index], reportSections[index - 1]] = [reportSections[index - 1], reportSections[index]];
        displayReport();
    } else if (direction === 'down' && index < reportSections.length - 1) {
        [reportSections[index], reportSections[index + 1]] = [reportSections[index + 1], reportSections[index]];
        displayReport();
    }
}

function previewReport() {
    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
    const previewContent = document.getElementById('previewContent');
    
    // 生成预览HTML
    let html = `
        <div class="container-fluid">
            <div class="report-header">
                <div class="report-title">${document.getElementById('reportTitle').value}</div>
                <div class="report-meta">
                    作者：${document.getElementById('reportAuthor').value} | 
                    生成时间：${new Date().toLocaleString()}
                </div>
            </div>
    `;
    
    reportSections.forEach(section => {
        html += `
            <div class="report-section">
                <div class="section-title">${section.title}</div>
                <div class="section-content">
                    ${renderSectionContent(section)}
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    previewContent.innerHTML = html;
    
    modal.show();
}



function saveReport() {
    const reportData = {
        title: document.getElementById('reportTitle').value,
        author: document.getElementById('reportAuthor').value,
        sections: reportSections,
        created_at: new Date().toISOString()
    };
    
    // 保存到本地存储
    localStorage.setItem(`report_${filename}`, JSON.stringify(reportData));
    
    alert('报告已保存');
}

function loadTemplate() {
    // 从本地存储加载报告
    const savedReport = localStorage.getItem(`report_${filename}`);
    if (savedReport) {
        const reportData = JSON.parse(savedReport);
        document.getElementById('reportTitle').value = reportData.title;
        document.getElementById('reportAuthor').value = reportData.author;
        reportSections = reportData.sections || [];
        displayReport();
        enableReportControls();
    } else {
        alert('没有找到已保存的报告');
    }
}

function printReport() {
    window.print();
}

function enableReportControls() {
    document.getElementById('previewBtn').disabled = false;
    document.getElementById('saveBtn').disabled = false;
}

function showAiInsightsNotification(insights) {
    // 创建AI洞察通知
    const notification = document.createElement('div');
    notification.className = 'alert alert-info alert-dismissible fade show position-fixed';
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 1050; max-width: 400px;';
    notification.innerHTML = `
        <div class="d-flex align-items-start">
            <i class="fas fa-brain me-2 mt-1"></i>
            <div>
                <strong>AI智能洞察已生成</strong>
                <p class="mb-1 small">发现了 ${insights.length} 个重要洞察点</p>
                <button class="btn btn-sm btn-outline-primary" onclick="scrollToAiInsights()">查看详情</button>
            </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // 5秒后自动消失
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

function scrollToAiInsights() {
    // 滚动到第一个AI洞察章节
    const aiInsightSection = document.querySelector('[data-section-type="ai_insight"]');
    if (aiInsightSection) {
        aiInsightSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
        // 高亮显示
        aiInsightSection.style.boxShadow = '0 0 20px rgba(0, 123, 255, 0.3)';
        setTimeout(() => {
            aiInsightSection.style.boxShadow = '';
        }, 2000);
    }
}



function enhanceReportWithAI() {
    if (!filename || filename.trim() === '') {
        alert('请先生成基础报告');
        return;
    }
    
    // 显示AI增强进度
    const enhanceBtn = document.createElement('button');
    enhanceBtn.className = 'btn btn-outline-primary btn-sm';
    enhanceBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>AI增强中...';
    enhanceBtn.disabled = true;
    
    fetch(`/api/enhance-report/${filename}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            sections: reportSections
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('AI增强失败：' + data.error);
        } else {
            // 添加AI增强的章节
            if (data.enhanced_sections) {
                reportSections = reportSections.concat(data.enhanced_sections);
                displayReport();
                showAiInsightsNotification(data.enhanced_sections);
            }
        }
    })
    .catch(error => {
        alert('AI增强失败：' + error.message);
    });
}
</script>
{% endblock %}